﻿using System;
using System.Collections.Generic;
using System.Text;
using Xeno.Core;
using Xeno.Maths;
using Xeno.Module;
using Xeno.GUI;

using OpenTK;
using OpenTK.Audio;
using OpenTK.Graphics;
using OpenTK.Input;
using OpenTK.Platform;
using OpenTK.Math;
using PhysX.NET;
namespace Xeno.Physics
{
    public class XenoRigidBody : XenoModule
    {

        public NxBodyDesc Body { get; set; }
        public NxActorDesc ActorDesc { get; set; }
        public NxActor Actor { get; set; }
        public XenoRigidBody(string name,XenoNode attached,bool isStatic,float mass)
        {
          
            Attached = attached;
            XenoCollider cod = Attached.Collider;
     
            List<XenoNode> managers = Attached.GraphOwner.RootNode.AllWithType(typeof(XenoPhysicsManager), null);
            XenoNode man = managers[0];

            if (!isStatic)
            {
                Body = new NxBodyDesc();
                Body.angularDamping = 0.5f;
            }
            
            ActorDesc = new NxActorDesc();
            ActorDesc.shapes.pushBack(cod.Shape);

            if (!isStatic)
            {
                ActorDesc.body = Body;
            }
            ActorDesc.density = 10.0f;

            Matrix4 mat = attached.LocalRotation;

            NxMat34 xmat = new NxMat34();
            NxMat33 rmat = new NxMat33();
            rmat._11 = mat.M11;
            rmat._12 = mat.M12;
            rmat._13 = mat.M13;
            rmat._21 = mat.M21;
            rmat._22 = mat.M22;
            rmat._23 = mat.M23;
            rmat._31 = mat.M31;
            rmat._32 = mat.M32;
            rmat._33 = mat.M33;
            xmat.M = rmat;
            NxVec3 pos = new NxVec3();
            pos.x = attached.LocalPosition.X;
            pos.y = attached.LocalPosition.Y;
            pos.z = attached.LocalPosition.Z;
            xmat.t = pos;

            ActorDesc.globalPose = xmat;

            Actor = man.PhysicsManager.Scene.createActor(ActorDesc);
           


        }

        public override void DoUpdate()
        {

            NxMat34 mat = Actor.getGlobalPose();
            Matrix4 rmat = Matrix4.Identity;
            rmat.M11 = mat.M._11;
            rmat.M12 = mat.M._12;
            rmat.M13 = mat.M._13;
            rmat.M21 = mat.M._21;
            rmat.M22 = mat.M._22;
            rmat.M23 = mat.M._23;
            rmat.M31 = mat.M._31;
            rmat.M32 = mat.M._32;
            rmat.M33 = mat.M._33;
            Attached.LocalRotation = rmat;
            Attached.LocalPosition = new Vector3(mat.t.x, mat.t.y, mat.t.z);

          

        }

    }
}
